extends Position3D

var followed_object: Spatial = null
onready var camera: Camera = $Camera

export(float) var view_dist: float = 11.8
export(float) var view_dist_max: float = 25.0
export(float) var view_dist_min: float = 5.0

export(float) var view_rot_x_in_deg: float = -50.0

export(float) var view_rot_y_in_deg: float = 0.0

onready var view_dist_anim: float = view_dist
onready var view_rot_x_in_deg_anim: float = view_rot_x_in_deg
onready var view_rot_y_in_deg_anim: float = view_rot_y_in_deg

func _input(event):
	if event.is_action_pressed("game_wheel_up"):
		view_dist /= 1.1
	elif event.is_action_pressed("game_wheel_down"):
		view_dist *= 1.1
	elif event.is_action_pressed("game_view_left"):
		view_rot_y_in_deg -= 90.0
	elif event.is_action_pressed("game_view_right"):
		view_rot_y_in_deg += 90.0

# warning-ignore:unused_argument
func _process(delta):
	view_dist = clamp(view_dist, view_dist_min, view_dist_max)

	view_dist_anim = lerp(view_dist_anim, view_dist, 0.2)
	view_rot_x_in_deg_anim = lerp(view_rot_x_in_deg_anim, view_rot_x_in_deg, 0.2)
	view_rot_y_in_deg_anim = lerp(view_rot_y_in_deg_anim, view_rot_y_in_deg, 0.2)

	if view_rot_y_in_deg_anim >= 300.0 and view_rot_y_in_deg >= 300.0:
		view_rot_y_in_deg_anim -= 360.0
		view_rot_y_in_deg -= 360.0
	elif view_rot_y_in_deg_anim <= -300.0 and view_rot_y_in_deg <= -300.0:
		view_rot_y_in_deg_anim += 360.0
		view_rot_y_in_deg += 360.0

	if followed_object != null and "view_rot_y_in_deg" in followed_object:
		followed_object.view_rot_y_in_deg = view_rot_y_in_deg

	camera.transform.origin = Vector3(0, 0, view_dist_anim)
	if followed_object != null:
		var xf: Transform = Transform()
		xf.origin = followed_object.global_transform.origin
		global_transform = xf
	else:
		transform = Transform()
	rotate_x(deg2rad(view_rot_x_in_deg_anim))
	rotate_y(deg2rad(view_rot_y_in_deg_anim))
